<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace suifeng\builder\form\control;

use suifeng\builder\form\Control;
use suifeng\helper\HtmlHelper;

class Toggle extends Control
{
    /**
     * 被选择时，应该返回的值。
     * @var integer
     */
    public $checked_value = 1;

    /**
     * 未被选择时，应该返回的值。
     * @var integer
     */
    public $unchecked_value = 0;

    /**
     * 输出HTML。
     *
     * @return string
     */
    protected function _render_core()
    {
        $toggle_id = $this->_get_control_id() . '_toggle';
        $input_id = $this->_get_control_id() . '_input';

        $attributes = $this->attributes;
        $attributes['name'] = $this->name;
        $attributes['value'] = $this->value;

        $checked = $this->value ? true : false;

        $toggle_attributes =  [
            'type'  =>  'checkbox',
            'id'    =>  $toggle_id,
        ];

        if ($this->value) {
            $toggle_attributes['checked'] = 'checked';
        }

        $content = HtmlHelper::render_tag('input', $toggle_attributes);
        $content .= HtmlHelper::render_tag('span', null, '');

        $content .= HtmlHelper::render_tag('input', [
            'type'  =>  'hidden',
            'id'    =>  $input_id,
            'name'  =>  $this->_get_formatted_name(),
            'value' =>  $this->value,
        ]);

        return <<<EOF
<div class="checkbox checkbox-slider--b-flat checkbox-slider-md">
    <label style="position: relative;">
        {$content}
    </label>
</div>

<script type="text/javascript">
$(function(){
    $(document).on('click', '#{$toggle_id}', function() {
        var ch = $(this).is(':checked');
        if (ch == true) {
            $('#{$input_id}').val('{$this->checked_value}');
        } else {
            $('#{$input_id}').val('{$this->unchecked_value}');
        }
    });
});
</script>
EOF;
    }
}

?>
